package com.online.shopping.service.impl;

import com.online.shopping.pojo.TbItem;
import com.online.shopping.service.ItemSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.Query;
import org.springframework.data.solr.core.query.SimpleQuery;
import org.springframework.data.solr.core.query.result.ScoredPage;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Rui
 * @version 1.0
 * @date 2020/11/20 13:26
 */
@Service
public class ItemSearchServiceImpl implements ItemSearchService {

    @Autowired
    private SolrTemplate solrTemplate;

    @Override
    public Map search(Map searchMap) { // ItemQuery.keywords
        Map map=new HashMap();

        Query query=new SimpleQuery("*:*");
        //item_keywords是solr的业务字段
        Criteria criteria=new Criteria("item_keywords").is(searchMap.get("keywords"));
        query.addCriteria(criteria);

        ScoredPage<TbItem> page = solrTemplate.queryForPage("collection1",query, TbItem.class);

        map.put("rows", page.getContent());

        return map;  //  json   {rows: [{},{},{},....  ]}
    }

    public void testQuery(){
        Query query = new SimpleQuery("*:*");
        Criteria criteria = new Criteria("item_title").endsWith("三星");
        query.setRows(100);
        query.addCriteria(criteria);

        Page<TbItem> itemPage = solrTemplate.query("collection1", query, TbItem.class);
        List<TbItem> itemList = itemPage.getContent();

        for (TbItem item : itemList) {
            System.out.println(item.getTitle() + "," + item.getPrice() + "," + item.getImage());
        }

    }
}
